<template>
  <view class="container">
    <view class="bgColor"></view>

    <view class="wrapper">
      <view class="steps">
        <view class="item" :class="steps == 1 ? 'active' : ''">
          <template>
            <view class="circle" v-if="steps > 1">
              <u-icon name="checkbox-mark" color="#FFF"></u-icon>
            </view>
            <view v-else class="circle">1</view>
          </template>
          <view class="title">身份信息</view>
          <template>
            <view class="rtline lineColor" v-if="steps == 2"></view>
            <view v-else class="rtline"></view>
          </template>
        </view>
        <view class="item" :class="steps == 2 ? 'active' : ''">
          <template>
            <view class="circle" v-if="steps == 1 || steps == 2">2 </view>
            <view class="circle" v-if="steps > 2">
              <u-icon name="checkbox-mark" color="#FFF"></u-icon>
            </view>
          </template>
          <view class="title">租房信息</view>
        </view>
      </view>

      <view class="wrapper-item content">
        <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
          <template v-if="steps == 1">
            <view class="sign-title" style="margin-top: 30rpx">出租方(甲方)：</view>

            <div class="cus-tag">房屋当前负责人</div>

            <view class="sign-title" style="margin-top: 30rpx">承租方(乙方)：</view>

            <div class="tag-wrap">
              <div class="cus-tag" v-for="item in select_list" @click="close_tag(item.fId)">
                <text>{{ item.fXm }}</text>
                <u-icon name="close" color="#FFF"></u-icon>
              </div>
              <div class="cus-tag cus-tag-plus" @click="handleClickRouter" :data-url="`/rentalHousing/select_tenant?tenant_list=${JSON.stringify(
                  tenant_list
                )}&check_list=${JSON.stringify(check_list)}`">
                <u-icon name="plus" color="#2488F5"></u-icon><text>添加人员</text>
              </div>
            </div>
          </template>

          <template v-if="steps == 2">
            <u-form-item label="租房时间" borderBottom :required="true" @click="datetimeShow = true">
              <u--input v-model="form.beginTime" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>

              <image :src="baseImgUrl + 'day-icon.png'" mode="" slot="right" class="seleTime"></image>
            </u-form-item>

            <u-form-item label="租期(月)" borderBottom :required="true">
              <u--input v-model="form.leaseTerm" type="number" :maxlength="5" placeholder="请填写租住月数"
                border="none"></u--input>
            </u-form-item>

            <u-form-item label="房租(元)" borderBottom :required="true">
              <u--input v-model="form.rentalRent" type="number" :maxlength="10" placeholder="请填写月租"
                border="none"></u--input>
            </u-form-item>

            <u-form-item label="租房用途" borderBottom :required="true"
              @click="handel_picker_show('rental_use', 'rentUse')">
              <u--input v-model="form.rentUse_dict" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>

            <u-form-item label="月租支付期限" borderBottom @click="handel_picker_show('pay_picker', 'paymentTerm')">
              <u--input v-model="form.paymentTerm_dict" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>

            <u-form-item label="租房押金(元)" borderBottom>
              <u--input v-model="form.securityDeposit" :maxlength="20" placeholder="请填写租房押金" border="none"></u--input>
            </u-form-item>

            <u-form-item label="租房合同" borderBottom :required="true" @click="
                handel_picker_show('rent_contract_type', 'rentContractType')
              ">
              <u--input v-model="form.rentContractType_dict" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>

            <div class="upload" v-if="form.rentContractType == 1">
              <view style="padding-top: 20rpx"></view>
              <u-form-item label="场所内部照片">
                <text style="color: #a1a1a1; font-size: 26rpx">
                  (请上传1~9张照片)
                </text>
              </u-form-item>
              <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="9"
                :multiple="true" width="96" height="90">
                <image :src="baseImgUrl + 'upload-icon2.png'" style="width: 200rpx; height: 180rpx"></image>
              </u-upload>
            </div>
          </template>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button v-if="steps == 1" class="submit-btn" type="primary" @click="nextSteps(1)" icon="map" style="width: 100%">
        下一步
      </button>

      <block v-if="steps == 2">
        <button class="previous-btn lt" type="primary" @click="steps = 1">
          上一步
        </button>

        <button class="submit-btn" type="primary" @click="generate_contract"
          v-if="form.rentContractType == 2 && is_generate_contract == false">
          生成电子合同
        </button>

        <button class="submit-btn" type="primary" @click="submitHandle" v-else>
          提交
        </button>
      </block>
    </view>

    <u-picker :show="pickerShow" :columns="columns" :keyName="keyName" @confirm="showConfirm" @close="pickerClose"
      @cancel="pickerClose" :closeOnClickOverlay="true" @change="handlePickerChange"></u-picker>

    <u-datetime-picker mode="date" :minDate="minDate" :maxDate="maxDate" :show="datetimeShow" v-model="timeValue"
      :formatter="formatter" @close="pickerTimeClose" @cancel="pickerTimeClose" @confirm="showTimeConfirm"
      :closeOnClickOverlay="true"></u-datetime-picker>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    getAction,
    postAction
  } from "@/utils/request.js";
  import {
    ajaxGetDictItems
  } from "@/api/api.js";
  import {
    config
  } from "../config.js";
  import {
    Toast,
    navBack,
    handleClickRouter,
    checkIDCard,
    formatters,
    dayTurnTime,
    uploadFile,
  } from "@/utils/util.js";
  import moment from "@/utils/moment.js";
  export default {
    data() {
      return {
        steps: 1,
        fHouseid: "",
        fDzbm: "",
        form: {
          rentHouseId: "",
          fDzbm: "",

          rentContract: "", // 主要负责人id
          hostName: "", // 主要负责人名称
          hostMobile: "", // 主要负责人手机号
          hostIdcard: "", // 主要负责人身份证号

          beginTime: "", // 租房开始时间
          endTime: "", // 租房结束时间

          leaseTerm: "", // 租期
          rentalRent: "", // 租金
          rentUse: "", // 用途

          paymentTerm: "", // 月租支付期限
          securityDeposit: "", // 租房保证金
          rentContractType: "", //  合同类型(0.无合同，1.上传合同图片，2.在线合同)

          tenantList: [], // 租客列表
          rentContractImage: "",
        },
        errorType: ["none"],
        baseURL: this.$baseURL,
        baseImgUrl: this.$baseImgUrl,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        role: uni.getStorageSync("role") || "fj",

        check_list: [], // 保存选择的租客id 用来点入回显
        select_list: [], // 保存选择的租客id
        tenant_list: [], // 所有的租客信息
        host_info: {}, // 主租人信息

        datetimeShow: false,
        timeValue: Number(new Date()),
        minDate: null,
        maxDate: new Date(2099, 12, 1).getTime(),

        pickerShow: false,
        columns: [],
        keyName: "title",
        form_type: "",
        pay_picker: this.initPayModel(),
        rent_contract_type: [{
            title: "无租房合同",
            value: "0"
          },
          {
            title: "上传合同图片",
            value: "1"
          },
          {
            title: "在线签署电子版合同",
            value: "2"
          },
        ],

        file2Num: 0, // 记录长传图片张数
        fileList: [], // 上传图片列表
        interiorUrlList: [],

        is_generate_contract: false,
        options: {}
      };
    },
    onLoad(options) {
      this.fHouseid = options.fHouseid;
      this.fDzbm = options.fDzbm;
      this.options = options
      this.get_tenant_list();
      this.get_lessor_list();
      this.get_dict();

      uni.$on("electronic_contract_submit", (data) => {
        let {
          form,
          select_list
        } = data;
        this.form = form;
        this.select_list = select_list;
        this.is_generate_contract = true;
      });

      uni.$on("select_tenant", (e) => {
        this.check_list = e;
        this.select_list = this.tenant_list.filter((item) => {
          return e.includes(item.fId);
        });
      });
    },
    onUnload() {
      uni.$off("select_tenant");
      uni.$off("electronic_contract_submit");
    },
    onShow() {},
    methods: {
      handleClickRouter,
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },

      pickerTimeClose(e) {
        this.form.beginTime = "";
        this.datetimeShow = false;
      },

      showTimeConfirm(e) {
        this.form.beginTime = formatters(e.value, "YY/MM/DD");
        this.datetimeShow = false;
      },

      async get_dict() {
        let {
          result: rental_use
        } = await ajaxGetDictItems({
          code: "rental_use",
        });
        this.rental_use = rental_use;
      },

      get_dict_type(list, type) {
        let res = list.find((item) => item.value == type);
        if (res && res.title) {
          return res.title;
        } else {
          return "暂无";
        }
      },

      async get_tenant_list() {
        let res = await getAction("/rentinghouse/tenantList", {
          rentHouseId: this.fHouseid,
        });
        this.tenant_list = res.result;
      },

      async get_lessor_list() {
        let {
          result
        } = await getAction("/rentinghouse/lessorList", {
          id: this.fHouseid,
        });
        this.host_info = result[0];
      },

      handel_picker_show(list, form_type) {
        this.form_type = form_type;
        this.columns[0] = this[list];
        this.pickerShow = true;
      },

      pickerClose(e) {
        this.pickerShow = false;
      },

      showConfirm(e) {
        let obj = e.value[0];
        this.$set(this.form, this.form_type + "_dict", obj.title);
        this.$set(this.form, this.form_type, obj.value);
        this.pickerShow = false;
      },

      close_tag(id) {
        const check_list_index = this.check_list.indexOf(id);
        this.check_list.splice(check_list_index, 1);
        const select_list_index = this.select_list.findIndex(
          (item) => item.fId == id
        );
        this.select_list.splice(select_list_index, 1);
      },

      nextSteps(step) {
        this.form.fDzbm = this.fDzbm;
        this.form.rentHouseId = this.fHouseid;
        this.form.rentContract = this.host_info.id;
        this.form.hostName = this.host_info.userName;
        this.form.hostMobile = this.host_info.phone;
        this.form.hostIdcard = this.host_info.idCard;

        if (!this.form.rentContract) {
          Toast("请添加房屋负责人");
          return;
        }

        if (this.check_list.length == 0) {
          Toast("请选择租客");
          return;
        }

        this.steps = 2;
      },

      afterRead(info) {
        const header = {
          "content-type": "application/json", // 默认值
        };
        let token = uni.getStorageSync("X-MINI-TOKEN");
        let role = config.role;
        if (token) {
          const requestTokenName = config.roleConfig[role].requestTokenName;
          header[requestTokenName] = token;
        }
        this.file2Num += info.file.length;
        for (let v of info.file) {
          uploadFile({
              url: "/web/sys/upload/upload_file",
              filePath: v.url,
              name: "file",
              formData: {
                type: 67
              }
            })
            .then((res) => {
              let {
                fullPath,
                halfPath
              } = res.result;
              this.fileList.push({
                url: fullPath
              });
              this.interiorUrlList.push(halfPath);
            })
            .finally(() => {})
        }
      },

      deletePic(e) {
        this.fileList.splice(e.index, 1);
        this.interiorUrlList.splice(e.index, 1);
        this.file2Num -= 1;
      },

      set_end_time() {
        const inputDate = this.form.beginTime;
        const monthsToAdd = this.form.leaseTerm;
        this.form.endTime = moment(inputDate)
          .add(monthsToAdd, "months")
          .format("yyyy/MM/DD");
      },

      checkForm() {
        if (!this.form.beginTime) {
          Toast("请选择租房开始时间");
          return false;
        }
        if (!this.form.leaseTerm) {
          Toast("请选择租期");
          return false;
        }
        if (!this.form.rentalRent) {
          Toast("请填写月租");
          return false;
        }
        if (!this.form.rentUse) {
          Toast("请选择租房用途");
          return false;
        }
        if (!this.form.rentContractType) {
          Toast("请选择租房合同类型");
          return false;
        }
        return true;
      },

      generate_contract() {
        if (!this.checkForm()) return;

        this.set_end_time();

        uni.navigateTo({
          url: `/rentalHousing/electronic_contract?form=${JSON.stringify(
          this.form
        )}&select_list=${JSON.stringify(this.select_list)}&type=add&isMain=${this.options.isMain}`,
        });
      },

      async submitHandle() {
        if (!this.checkForm()) return;

        this.set_end_time();

        if (this.form.rentContractType == 1 && this.fileList.length == 0) {
          Toast("请上传合同图片");
          return;
        }

        if (this.form.rentContractType == 2 && !this.is_generate_contract) {
          Toast("请生成电子合同");
          return;
        }

        this.form.tenantList = this.select_list.map((item) => {
          return {
            tenantId: item.fId,
            tenantryName: item.fXm,
            tenantryMobile: item.fLxdh,
            tenantryIdcard: item.fGmsfhm,
            tenantrySign: item.tenantrySign,
          };
        });

        this.form.rentContractImage = this.interiorUrlList.join(",") || "";

        const res = await postAction("/rentinghouse/addRentContract", this.form);
        Toast(res.message);
        uni.$emit("add_rental_info_success");
        navBack();
      },
      handlePickerChange(e) {
        let index = e.index
      },
      initPayModel() {
        return new Array(31).fill(1).map((item, index) => ({
          title: `每月${index + 1}日前`,
          value: index + 1
        }))
      }
    },
  };
</script>

<style scoped lang="scss">
  .tag-wrap {
    display: flex;
    flex-wrap: wrap;
  }

  .cus-tag {
    width: fit-content;
    padding: 12rpx 26rpx;
    margin: 30rpx 30rpx 30rpx 0;
    font-weight: 500;
    font-size: 30rpx;
    border-radius: 44rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;

    background: #2488f5;
    border: 1rpx solid #1f78d9;

    display: flex;
    justify-content: center;
    align-items: center;

    text {
      margin-right: 16rpx;
    }
  }

  .cus-tag-plus {
    background: #f6faff;
    border: 1rpx solid #deeeff;

    color: #2488f5;

    text {
      margin-left: 16rpx;
    }
  }

  .bgColor {
    width: 100%;
    height: 240rpx;
    background: #2488f5;
  }

  .wrapper {
    position: absolute;
    top: 30rpx;
    left: 50%;
    transform: translateX(-50%);

    .wrapper-item {
      // margin-bottom: 2vh;
      padding: 35rpx 30rpx;
      padding-left: 36rpx;
      background-color: #ffffff;
      box-shadow: 0px 3px 6px 1px rgba(123, 123, 123, 0.2);
      border-radius: 10rpx;
      width: 710rpx;
      height: 922rpx;
      overflow: auto;
    }

    .steps {
      display: flex;
      justify-content: space-between;
      margin: 0 auto;

      .item {
        flex: 1;
        position: relative;
        top: 0;
        left: 0;

        .title {
          font-size: 25rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #a7cffb;
          text-align: center;
          margin-bottom: 10rpx;
          margin-top: 10rpx;
        }

        .circle {
          display: flex;
          justify-content: center;
          align-items: center;

          width: 80rpx;
          height: 80rpx;
          margin: 0 auto;
          font-size: 32rpx;
          border-radius: 50%;
          background: #a7cffb;
          color: #24adfa;
        }

        .ltline {
          position: absolute;
          bottom: 50rpx;
          left: 0;
          width: 38%;
          border-bottom: 13rpx dotted #a7cffb;
        }

        .rtline {
          position: absolute;
          bottom: 85rpx;
          right: -35rpx;
          width: 18%;
          border-bottom: 13rpx dotted #a7cffb;
        }
      }

      .active {
        .title {
          color: #fff;
        }

        .circle {
          background: #fff;
          color: #24adfa;
        }
      }

      .lineColor {
        border-bottom: 13rpx dotted #fff !important;
      }
    }
  }

  .thispageBtn {
    position: fixed;
    width: 100vw;
    bottom: 0;
    left: 0;
  }

  .sign-title {
    font-weight: bold;
    font-size: 28rpx;
    color: #000000;
  }

  .seleTime {
    width: 30rpx;
    height: 30rpx;
  }
</style>